using System;
using System.Collections.Generic;
using System.Text;
using SqlTools.DataAccessLibrary;
using System.Data;
using SqlTools.SampleDAL.Data;

namespace SqlTools.SampleDAL
{
	public partial class Role : BusinessObject, IDbObject<RolePrimaryKey>
	{
		protected RolePrimaryKey _rolePrimaryKey;
		protected string _name;
		protected DbList<User_Role> _user_roles;

		public Role()
		{
			_rolePrimaryKey = new RolePrimaryKey();
			_name = "";
			_user_roles = null;
		}

		#region IDbObject<RolePrimaryKey> Members

		public RolePrimaryKey Key
		{
			get { return _rolePrimaryKey; }
		}

		#endregion

		public string Name
		{
			get { return _name; }
			set
			{
				_name = value;
				_UpdateState();
			}
		}

		public DbList<User_Role> User_Roles
		{
			get
			{
				if ( _user_roles == null )
				{
					DbUser_Role dbUser_Role;
					if ( !string.IsNullOrEmpty(_ConnectionStringName) )
						dbUser_Role = new DbUser_Role(_ConnectionStringName);
					else
						dbUser_Role = new DbUser_Role();

					_user_roles = dbUser_Role.SelectByRoleID(this.Key.RoleID);
				}

				return _user_roles;
			}
		}

		public override void Update()
		{
			OnUpdating(this);

			DbRole dbRole = CreateDbRole();
			dbRole.Update(this);

			OnUpdated(this);
		}

		public override void Insert()
		{
			OnInserting(this);

			DbRole dbRole = CreateDbRole();
			dbRole.Insert(this);

			OnInserted(this);
		}

		public override void Delete()
		{
			OnDeleting(this);

			DbRole dbRole = CreateDbRole();
			dbRole.Insert(this);

			OnDeleted(this);
		}

		protected DbRole CreateDbRole()
		{
			if ( !string.IsNullOrEmpty(_ConnectionStringName) )
				return new DbRole(_ConnectionStringName);
			else
				return new DbRole();
		}

		public static Role CreateFromReader(IDataReader reader)
		{
			Role role = new Role();

			FillFromReader(role, reader);

			return role;
		}

		public static void FillFromReader(Role role, IDataReader reader)
		{
			role.OnLoading(role);

			role.Key.RoleID = (int)reader["RoleID"];
			role._name = reader["Name"].ToString();

			role._UpdateState(ObjectState.None);

			role.OnLoaded(role);
		}
	}
}
